package com.ccit.greenlife.service.impl;

import com.ccit.greenlife.Mapper.UserMapper;
import com.ccit.greenlife.pojo.User;
import com.ccit.greenlife.service.UserService;
import com.ccit.greenlife.utils.Md5Util;
import com.ccit.greenlife.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.UUID;
import static java.time.LocalDateTime.now;

@Service
public class UserServicelmpl implements UserService {
    @Autowired
    //自动依赖注入
    private UserMapper userMapper;

    //获取用户信息
    @Override
    public User getUserInfo(String id) {
        User user = userMapper.getUserInfo(id);
        return user;
    }

    @Override//根据用户名查询用户
    public User findByUsername(String username) {
        User user = userMapper.findByUsername(username);
        return user;
    }

    //注册
    @Override
    public void register(String username, String password, String email) {
        User user = new User();
//        LocalDateTime now = LocalDateTime.now();// 获取当前时间
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyMMdd");// 定义时间格式
//        String timeStamp = now.format(formatter);// 格式化当前时间
//        String nickname = "用户" + timeStamp;// 生成昵称
        String nickname = "用户" + email.split("@")[0];// 生成昵称

        //填充信息
        user.setId(UUID.randomUUID().toString().replace("-","").toLowerCase());
        user.setNickname(nickname);
        user.setAvatar("/Avator/default.png");
        user.setUsername(username);
        //密码先加密
        user.setPassword(Md5Util.md5(password));
        user.setEmail(email);
        user.setLevel(0);
        user.setIsActive(1);
        user.setType(1);
        user.setExp(0);
        user.setCreateTime(now());
        user.setIntegral(0);

        //注册
        userMapper.add(user);
    }

    //更换密码(更新密码，记录endtime作为更改时间)
    @Override
    public void updatePwd(String newPwd) {
        //获取解析的id
        Map<String, Object> map = ThreadLocalUtil.get();
        String id = (String) map.get("id");
        userMapper.updatePwd(id, Md5Util.md5(newPwd));
    }

    //根据邮件查用户
    @Override
    public User findByEmail(String username) {
        User user = userMapper.findByEmail(username);
        return user;
    }

    @Override
    public void updateAvatar(String avatar) {
        //获取解析的id
        Map<String, Object> map = ThreadLocalUtil.get();
        String id = (String) map.get("id");
        userMapper.updateAvatar(avatar, id);
    }

    //更新用户信息
    @Override
    public void updateInfo(User user) {
        //获取解析的id
        Map<String, Object> map = ThreadLocalUtil.get();
        String id = (String) map.get("id");
        user.setId(id);
        userMapper.updateInfo(user);
    }

}
